/**
 * Created by xuchaosheng on 16/5/22.
 */
services.factory("tools", ["$http", "$rootScope", "$location", "$timeout", "Session", "$cookies","$q","$location", function($http, $rootScope,  $location,$timeout, Session, $cookie,$q,$location) {
    return {
        $post:function(param){

            if (!param instanceof Object || !param.url) {
                return;
            }  
       
            var defer = $q.defer();
            //{url:xx:data:{xx:xx}}          
            $http({
                method: 'post',
                url: param.url,
                data: param.data,
                headers:{'Content-Type': 'application/x-www-form-urlencoded'},
                transformRequest: function(obj) {    
                    var str = [];    
                    for (var p in obj) {    
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));    
                    }    
                    return str.join("&");    
                }   
            }).success(function(resp){
       
        
               
                if (resp.value == "session expired") {
                    Session.destroy();
                    window.location.href = '/index';
                    return;
                }
                if(resp.success){
                    defer.resolve(resp);
                }else{
                    defer.reject(resp);
                }
            },function(err){
                var resp = resp.data;
               
                defer.reject(err);
            });

            return defer.promise;
        },
        $get:function(param){

            if (!param instanceof Object || !param.url) {
                return;
            }
            var self = this;
            var defer = $q.defer();
            $http({
                method: 'GET',
                url: '/proxy'+param.url,
                params: param.data || {},
                headers: {
                    'Accept': 'application/json, text/javascript, */*'
                }
            }).success(function (resp) {
                // var resp = resp.data;
  
                if (resp.value == "session expired") {
                    Session.destroy();
                    $location.path('/login');
                    return;
                }
                if(resp.success){
                    defer.resolve(resp);
                }else{
                    defer.reject(resp);
                }
            },function (err) {
                defer.reject(err);
            });

            return defer.promise;
        },
        get: function(param) {
            var self = this;
            if (!param instanceof Object || !param.url) {
                return;
            }

            $rootScope.$broadcast('loading');

            $http({
                method: param.method || 'GET',
                params: param.data || {},
                url: '/proxy'+param.url,
                headers: {
                    'Accept': 'application/json, text/javascript, */*'
                }
            }).success(function(resp) {
                $rootScope.$broadcast('loading_off');

                if (resp.value == "session expire") {


                    if (location.hash.indexOf('reg') != -1 || location.hash.indexOf('forget') != -1) {
                        console.log('reg,login')
                        return;
                    }

                    var userInfo = Session.UserInfo;
                    if (!userInfo) {
                        console.log('login');
                        $location.path('/login');
                        // window.location.href = 'login.html';
                        // window.location.href = "/marketconditions/html/login.html";
                    } else {
                        if (userInfo.channel == "1") {
                            console.log('云起');
                            window.location.href = '/marketconditions/user/shopexLogin.htm' + window.location.search;
                        } else {
                            console.log('qushu')
                            window.location.href = 'login.html';
                            // window.location.href = "/marketconditions/html/login.html";
                        }
                        Session.destroy();
                    }

                }

                param.succ && param.succ(resp);
            }).error(function(resp) {
                param.fail && param.fail(resp);
            });
        },
        trim: function(str) {
            if (!str instanceof String)
                return str;

            var res = str.replace(/^\s+|\s+$/gi, "");
            return res;
        },
        isEmpty: function(obj) {
            for (var i in obj) {
                return false;
            }
            return true;
        },
        data: {
            data: {},
            setItem: function(key, value) {
                this.data[key] = value;
            },
            getItem: function(key) {
                return this.data[key];
            },
            delItem: function(key) {
                delete this.data[key];
            }
        },
        bigNumFormat: function(num) {
            num = Number(Number(num).toFixed(0));

            var len = String(num).length;

            if (num < 10000) {
                return num;
            }

            switch (len) {
                case 5:
                    return (num / 10000).toFixed(2) + '万';
                case 6:
                    return (num / 10000).toFixed(2) + '万';
                case 7:
                    return (num / 10000).toFixed(2) + '万';
                case 8:
                    return (num / 10000).toFixed(2) + '万';
                case 9:
                    return (num / 100000000).toFixed(2) + '亿';
                case 10:
                    return (num / 100000000).toFixed(2) + '亿';
                case 11:
                    return (num / 100000000).toFixed(2) + '亿';
                case 12:
                    return (num / 100000000).toFixed(2) + '亿';
            }

            return num;
        },
        format: function(time){
            var setTime = angular.isString(time)?time:time.toString();            
            
            return setTime.substring(0, 10);
        },
        historyStringObject:function(dataS){
            // var s = '2017-01-16=83966;2017-01-15=83966;2017-01-14=83966;2017-01-13=83966;2017-01-12=83966';
            var data = [];
            var cats = [];
            if(dataS.length>0){    
                //'2017-01-16=83966' 一条记录            
                if(dataS.indexOf(';') == -1){
                    var temp = dataS.split('=');
                    cats.push(temp[0]);
                    data.push(temp[1]);
                }else{
                    //多条记录
                    var arr = dataS.split(';');
                    for(var k in arr){
                        var temp = arr[k].split('=');
                        cats.push(temp[0]);
                        data.push(temp[1]);
                    }
                }
            }

            return {
                x:cats,
                y:data
            }
            
        }
    }
}]);
services.service('Session', ['$cookies', function($cookies) {

    if ($cookies.getObject('session')) {
        this.UserInfo = $cookies.getObject('session');
    }

    this.create = function(UserInfo) {
        this.UserInfo = UserInfo;
        var now = new Date();
        // this will set the expiration to 1 day
        now.setDate(now.getDate() + 1);
        $cookies.putObject('session', UserInfo, { 'expires': now });
    };
    this.destroy = function() {
        this.UserInfo = null;
        $cookies.remove('session');
    };

    return this;
}]);
services.factory('NoticeServ', ['$rootScope', function($rootScope) {
    return {
        //订阅
        $on: function(scope, eventName, callback) {
            if (!scope.Event_OFF) {
                scope.Event_OFF = [];
            }
            scope.Event_OFF[eventName] = $rootScope.$on(eventName, callback);
            scope.$on('$destroy', function() {
                // console.log(scope);
                for (var i in scope.Event_OFF) {
                    console.log('destory:' + i);
                    scope.Event_OFF[i]();
                }
            });
        },
        //发布 事件
        $broadcast: function(eventName, data) {
            $rootScope.$emit(eventName, data);
        }
    }
}]);
services.factory('utils', function() {
    return {
        //全屏
        toggleFullscreen:function(elem){
            elem = elem || document.documentElement;
            if (!document.fullscreenElement && !document.mozFullScreenElement &&
                !document.webkitFullscreenElement && !document.msFullscreenElement) {
                if (elem.requestFullscreen) {
                    elem.requestFullscreen();
                } else if (elem.msRequestFullscreen) {
                    elem.msRequestFullscreen();
                } else if (elem.mozRequestFullScreen) {
                    elem.mozRequestFullScreen();
                } else if (elem.webkitRequestFullscreen) {
                    elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            }
        }
    }
   
});
services.factory('SweetAlert', ['$rootScope', function ( $rootScope ) {

  //live-demos http://oitozero.github.io/ngSweetAlert/#/home
    /*

    demos
    SweetAlert.swal("Good job!", "You clicked the button!", "success");

        SweetAlert.swal({
           title: "Are you sure?",
           text: "Your will not be able to recover this imaginary file!",
           type: "warning",
           showCancelButton: true,
           confirmButtonColor: "#DD6B55",confirmButtonText: "Yes, delete it!",
           cancelButtonText: "No, cancel plx!",
           closeOnConfirm: false,
           closeOnCancel: false }, 
        function(isConfirm){ 
           if (isConfirm) {
              SweetAlert.swal("Deleted!", "Your imaginary file has been deleted.", "success");
           } else {
              SweetAlert.swal("Cancelled", "Your imaginary file is safe :)", "error");
           }
        });

    SweetAlert.swal({
       title: "Are you sure?",
       text: "Your will not be able to recover this imaginary file!",
       type: "warning",
       showCancelButton: true,
       confirmButtonColor: "#DD6B55",
       confirmButtonText: "Yes, delete it!",
       closeOnConfirm: false}, 
    function(){ 
       SweetAlert.swal("Booyah!");
    });
    SweetAlert.swal({
       title: "Sweet!",
       text: "Here's a custom image.",
       imageUrl: "http:://oitozero.com/avatar/avatar.jpg" });


    */

  var swal = window.swal;

  //public methods
  var self = {
    //arg3 warning error success info
    swal: function ( arg1, arg2, arg3 ) {
      $rootScope.$evalAsync(function(){
        if( typeof(arg2) === 'function' ) {
          swal( arg1, function(isConfirm){
            $rootScope.$evalAsync( function(){
              arg2(isConfirm);
            });
          }, arg3 );
        } else {
          swal( arg1, arg2, arg3 );
        }
      });
    },
    success: function(title, message) {
      $rootScope.$evalAsync(function(){
        swal( title, message, 'success' );
      });
    },
    error: function(title, message) {
      $rootScope.$evalAsync(function(){
        swal( title, message, 'error' );
      });
    },
    warning: function(title, message) {
      $rootScope.$evalAsync(function(){
        swal( title, message, 'warning' );
      });
    },
    info: function(title, message) {  
      $rootScope.$evalAsync(function(){
        swal( title, message, 'info' );
      });
    }
  };
  
  return self;
}]);